<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="98px"
    >
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="邀请人昵称" prop="inviterNickname">
        <el-input
          v-model="queryParams.inviterNickname"
          placeholder="请输入邀请人昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="item in statusDict"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="最后登录时间" prop="loginDate">
        <el-date-picker
          v-model="queryParams.loginDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button @click="sendSms"><Icon icon="ep:refresh" class="mr-5px" /> 群发短信</el-button>
        <el-button @click="sendMp"
          ><Icon icon="ep:refresh" class="mr-5px" /> 群发模板消息</el-button
        >
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['system:member:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:member:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column label="用户" align="center">
        <template #default="scope">
          <div class="w-full flex justify-center items-center gap-3">
            <img class="w-10 h-10 ml-4 rounded-full" :src="scope.row.avatar" />
            <div class="text-base min-w-20 text-left">{{ scope.row.nickname }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="手机号" align="center" prop="mobile" />

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag class="ml-2" :type="typeFormatter(scope.row.status)!.type">{{
            typeFormatter(scope.row.status)!.str
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="最后登录时间"
        align="center"
        prop="loginDate"
        :formatter="dateFormatter"
      />

      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
      />
      <el-table-column label="邀请人" align="center">
        <template #default="scope">
          <div class="w-full flex justify-center items-center gap-3">
            <img
              v-if="scope.row.inviterAvatar"
              class="w-10 h-10 ml-4 rounded-full"
              :src="scope.row.inviterAvatar"
            />
            <div class="text-base min-w-20 text-left">{{ scope.row.inviterNickname }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-hasPermi="['system:member:update']"
            @click="openForm('update', scope.row.id)"
          >
            详情
          </el-button>
          <!-- <el-button
            link
            type="danger"
            v-hasPermi="['system:member:delete']"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />

  <!-- 群发短信弹窗 -->
  <send-sms-form @sended="sended" ref="smsFormRef" />
  <!-- 群发公众号模板消息弹窗 -->
  <send-mp-template-form @sended="sended" ref="mpFormRef" />
</template>

<script setup lang="ts" name="ScrmMember">
import { statusDict } from './common'
import { dateFormatter } from '@/utils/formatTime'
import * as MemberApi from '@/api/scrm/member/index'
import { SendSmsForm } from '@/components/SendSmsForm'
import { SendMpTemplateForm } from '@/components/SendMpTemplateForm'
import UserForm from './member-form.vue'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 表格基操
const tableRef = ref() // 表格的ref
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  inviterNickname: null,
  nickname: null,
  avatar: null,
  status: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  openid: '',
  isStudent: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MemberApi.getMemberPage(queryParams)
    console.log(data)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await UserApi.deleteUser(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 导出按钮操作 */
const handleExport = async () => {
  // try {
  //   // 导出的二次确认
  //   await message.exportConfirm()
  //   // 发起导出
  //   exportLoading.value = true
  //   const data = await UserApi.exportUser(queryParams)
  //   download.excel(data, '用户.xls')
  // } catch {
  // } finally {
  //   exportLoading.value = false
  // }
}

/** 表格项服务类型格式化  1 正式学员 2 普通用户 */
const typeFormatter = (val: number) =>
  ({
    0: {
      str: '正常',
      type: 'success'
    },
    1: {
      str: '停用',
      type: 'info'
    }
  }[val])

// 多选相关
const multipleSelection = ref<MemberApi.MemberVO[]>([]) // 表格的选择项
const sendPhoneList = ref<string[]>([]) // 发送短信的手机号列表
const openidList = ref<string[]>([]) // 发送模板消息的openid列表

/** 表格的选择项 */
const handleSelectionChange = (val: MemberApi.MemberVO[]) => {
  multipleSelection.value = val
  sendPhoneList.value = val.map((item) => item.mobile)
  openidList.value = val.map((item) => item.openid)
}

/** 群发短信 */
const smsFormRef = ref()
const sendSms = () => {
  let type: 'check' | 'uncheck' = 'uncheck' // 是否勾选了用户
  let params = queryParams
  let num = total.value * queryParams.pageSize
  if (multipleSelection.value.length > 0) {
    type = 'check'
    params = sendPhoneList.value
    num = multipleSelection.value.length
  }
  smsFormRef.value.open(type, params, num)
}

/** 群发微信公众号模板消息 */
const mpFormRef = ref()
const sendMp = () => {
  let type: 'check' | 'uncheck' = 'uncheck' // 是否勾选了用户
  let params = queryParams
  let num = total.value * queryParams.pageSize
  if (multipleSelection.value.length > 0) {
    type = 'check'
    params = sendPhoneList.value
    num = multipleSelection.value.length
  }
  mpFormRef.value.open(type, params, num)
}

/** 信息发送成功回调 */
const sended = () => {
  tableRef.value!.clearSelection()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
